package com.visionork.android.twe.activity;

import java.util.ArrayList;
import java.util.List;

import com.visionork.rss.FeedParser;
import com.visionork.rss.FeedParserFactory;
import com.visionork.rss.Message;
import com.visionork.rss.ParserType;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class WhatsNewActivity extends ListActivity {
	private final static String _feedUrl = "http://feeds.feedburner.com/twsugoideas?format=xml";
	private ProgressDialog _pd;
	private List<Message> _messages;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_list);
		load_feed();
		
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		ShowSchedule schedule = _schedule_list.get(position);
		Intent intent = new Intent(this, EpisodeActivity.class);
		intent.putExtra(EpisodeActivity.EPISODE_TITLE, schedule.get_title());
		intent.putExtra(EpisodeActivity.EPISODE_URL, schedule.get_url());
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.show_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected (MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			load_feed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private class LoadFeedTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			_schedule_list = new ArrayList<ShowSchedule>();
			FeedParser parser = FeedParserFactory.getParser(
					ParserType.ANDROID_SAX, _feedUrl);
			_messages = parser.parse();
			return null;
		}

		@Override
		protected void onPreExecute() {
			_pd = ProgressDialog.show(WhatsNewActivity.this, "加载中...", "读取最新列表", true, false);
		}
		@Override
		protected void onPostExecute(Void param) {
			List<String> titles = new ArrayList<String>(_messages.size());
			for (Message msg : _messages) {
				_schedule_list.add(new ShowSchedule(msg.getTitle(), msg
						.getLink().toExternalForm()));
				titles.add(msg.getTitle());
			}

			setListAdapter(new ArrayAdapter<String>(WhatsNewActivity.this,
					R.layout.show_list_item, titles));
			
			_pd.dismiss();
		}
	}

	private void load_feed() {
		LoadFeedTask task = new LoadFeedTask();
		task.execute(new Void[] {});
	}

	private ArrayList<ShowSchedule> _schedule_list;
}
